package com.spmsys.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

/**
 * 结果集合与json互转类
 */
public class ResultSetTurnJSON {
    /**
     * 结果集合转json对象
     *
     * @param resultSet 结果集合
     * @return json对象
     */
    public static JSONObject resultSetToJSONObject(@NotNull ResultSet resultSet) {
        try {
            JSONObject jsonObject = new JSONObject();
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            int columnCount = resultSetMetaData.getColumnCount();
            if (resultSet.next()) {
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = resultSetMetaData.getColumnLabel(i);
                    Object value = resultSet.getObject(columnName);
                    jsonObject.put(columnName, value);
                }
                jsonObject = JSONObject.parseObject(JSONObject.toJSONString(jsonObject, SerializerFeature.WriteMapNullValue));
            }
            //返回数据
            return jsonObject;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 结果集合转json数组
     *
     * @param resultSet 结果集合
     * @return json数组
     */
    public static @NotNull JSONArray resultSetToJSONArray(@NotNull ResultSet resultSet) {
        try {
            JSONArray jsonArray = new JSONArray();
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            int columnCount = resultSetMetaData.getColumnCount();
            while (resultSet.next()) {
                JSONObject jsonObject = new JSONObject();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = resultSetMetaData.getColumnLabel(i);
                    Object value = resultSet.getObject(columnName);
                    jsonObject.put(columnName, value);
                }
                jsonArray.add(JSONObject.parseObject(JSONObject.toJSONString(jsonObject, SerializerFeature.WriteMapNullValue)));
            }
            //返回数据
            return jsonArray;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * json对象转结果集合
     *
     * @param jsonObject json对象
     * @return 结果集合
     */
    @Contract(pure = true)
    public static @Nullable ResultSet JSONObjectToResultSet(JSONObject jsonObject) {
        return null;
    }

    /**
     * json数组转结果集合
     *
     * @param jsonArray json数组
     * @return 结果集合
     */
    @Contract(pure = true)
    public static @Nullable ResultSet JSONArrayToResultSet(JSONArray jsonArray) {
        return null;
    }

}
